//
//  MapViewController.m
//  Zyachting
//
//  Created by hungnt47 on 11/10/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"
#import "AddressAnnotation.h"
#import "JSON.h"
#import "ItemCell.h"
#import "UIImageView+WebCache.h"
@implementation MapViewController
@synthesize mapView,items;
@synthesize tableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Map", @"Map");
        self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"Map" image:[UIImage imageNamed:@"74-location.png"] tag:1] autorelease];            
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [HUD setLabelText:@"Loading"];
    [self.view addSubview:HUD];
    UIBarButtonItem* right = [[UIBarButtonItem   alloc] initWithTitle:@"List" style:UIBarButtonItemStyleBordered target:self action:@selector(listBtnTapped:)];
    self.navigationItem.rightBarButtonItem = right;
    [self getAllItems];
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    // Do any additional setup after loading the view from its nib.
}
-(IBAction)listBtnTapped:(id)sender
{
    if ([sender tag] == 0) {
        //CurrentMap
        self.mapView.hidden = YES;
        [sender setTag:1];
        [(UIBarButtonItem*)sender setTitle:@"Map"];
    }else{
        self.mapView.hidden = NO;
        [sender setTag:0];
        [(UIBarButtonItem*)sender setTitle:@"List"];
    }
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark TableView DataSource Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ItemCellIdentifier = @"ItemCellIdentifier";
    ItemCell *cell = (ItemCell *)[tableView1
                                              dequeueReusableCellWithIdentifier: ItemCellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ItemCell"
                                                     owner:self options:nil];
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[ItemCell class]])
                cell = (ItemCell *)oneObject;
    }
    NSDictionary* tmpDict = [self.items objectAtIndex:indexPath.row];
    cell.lblTitle.text = [tmpDict objectForKey:@"city"];
    NSInteger price = [[tmpDict objectForKey:@"price"] integerValue];
    cell.lblPrice.text = [NSString stringWithFormat:@"€ %d",price];
    NSInteger bedroom = [[tmpDict objectForKey:@"beds"] integerValue];
    cell.lblBedroom.text = [NSString stringWithFormat:@"%d bedrooms",bedroom];
    cell.lblRefID.text = [NSString stringWithFormat:@"ReferrenceID %@",[tmpDict objectForKey:@"mls_id"]];
    NSString* imageString = [tmpDict objectForKey:@"image"];
    [cell.ivImage setImageWithURL:[NSURL URLWithString:imageString] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;  
}

#pragma mark -
#pragma mark TableView Delegate Method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
#pragma mark - Helper
-(void)setupMapView
{
	/// MAP ////
    //define span for map: how much area will be shown
    MKCoordinateSpan span;
    span.latitudeDelta =.005;
    span.longitudeDelta=.005;
    
    // define starting point for map
	//Change here for the User Location
    CLLocationCoordinate2D start;
    start = self.mapView.userLocation.coordinate;

#if TARGET_IPHONE_SIMULATOR
    start.longitude = -0.6504678726196289;
    start.latitude = 38.00367022938047;
#endif
    // create region, consisting of span and location
    MKCoordinateRegion region;
    region.span = span;
    region.center = start;  
    
    //Move the map to our location //
    [mapView setRegion:region animated:YES];
    
    //show user location
    [mapView setShowsUserLocation:YES];
    
    for (int i =0; i< self.items.count; i++) {
        NSDictionary* tmpDict = [self.items objectAtIndex:i];
        CLLocationCoordinate2D pinLocation;
        pinLocation.latitude = [[tmpDict objectForKey:@"latitude"] doubleValue];
        pinLocation.longitude = [[tmpDict objectForKey:@"longitude"] doubleValue];
        AddressAnnotation* anotation = [[AddressAnnotation alloc] initWithCoordinate:pinLocation];
        [anotation setTitle:[tmpDict objectForKey:@"mls_id"]];
        NSInteger price = [[tmpDict objectForKey:@"price"] integerValue];
        NSString* town = tmpDict[@"city"];
        [anotation setSubTitle:[NSString stringWithFormat:@"%@\n \n€ %d",town,price]];
        [mapView addAnnotation:anotation];
        [anotation release];
    }
	
}
-(void)getAllItems
{
    [HUD show:YES];
    ASIHTTPRequest* request= [ASIHTTPRequest requestWithURL:[NSURL URLWithString:kSEARCHURL]];
    [request setDelegate:self];
    [request startAsynchronous];
}
#pragma mark - ASIHttpRequest Delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    self.items = [request.responseString JSONValue];
    [self setupMapView];
    [self.tableView reloadData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Connection Fail. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView1 viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *pinView = nil;
    if(annotation != mapView1.userLocation)
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKAnnotationView *)[mapView1 dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil )
            pinView = [[MKAnnotationView alloc]
                       initWithAnnotation:annotation reuseIdentifier:defaultPinID];
        
        //        pinView.pinColor = MKPinAnnotationColorGreen;
        pinView.canShowCallout = YES;
        //        pinView.animatesDrop = YES;
        pinView.image = [UIImage imageNamed:@"HouseIcon.png"];    //as suggested by Squatch
        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [rightButton addTarget:self
                        action:@selector(showDetails:)
              forControlEvents:UIControlEventTouchUpInside];
        pinView.rightCalloutAccessoryView = rightButton;
        
    }
    else {
        [mapView1.userLocation setTitle:@"I am here"];
    }
    return pinView;
}

-(IBAction)showDetails:(id)sender
{
    NSLog(@"Show Detail");
}
@end
